package com.sunnyebuy.merchant.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

/**
 * <p>
 * Title: CommonUtil.java
 * </p>
 * 
 * <p>
 * Description: com.sunnyebuy.merchant.util
 * </p>
 * 
 * <p>
 * Copyright: Copyright (c) 2008-2011 All rights reserved.
 * </p>
 * 
 * <p>
 * Created: 2011-12-28 上午10:57:45
 * </p>
 * 
 * @author Wenzhong Gu
 * 
 * @version 1.0
 */
public class CommonUtil {

	/***************************************************
	 * 获得UUID，用于上传文件的名称等需要唯一值的操作
	 **************************************************/
	public static String getUUID() {
		String uuid = UUID.randomUUID().toString();
		return uuid.substring(0, 8) + uuid.substring(9, 13) + uuid.substring(14, 18) + uuid.substring(19, 23)
				+ uuid.substring(24);
	}

	public static String getDate(Date date, String format) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);
		return dateFormat.format(date);
	}

	// Base64encode
	public static String base64Encoding(String s) {
		Base64 b64 = new Base64();
		return new String(b64.encode(s.getBytes()));
	}

	// Base64decode
	public static String base64Decoding(String s) {
		Base64 b64 = new Base64();
		return new String(b64.decode(s.getBytes()));
	}

	// MD5
	public static String md5(String s) {
		return DigestUtils.md5Hex(s.getBytes());
	}

	// Email
	public static boolean isEmail(String mail) {
		if (mail == null) {
			return false;
		} else {
			Pattern p = Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}");
			Matcher m = p.matcher(mail.toLowerCase());
			return m.matches();
		}
	}

	/****************************************
	 * 判断是不是整数
	 ***************************************/
	public static boolean isInteger(String str) {
		if (str == null) {
			return false;
		}
		Pattern pattern = Pattern.compile("[0-9]+");
		return pattern.matcher(str).matches();
	}

	/****************************************
	 * 判断是不是小数
	 ***************************************/
	public static boolean isFloat(String str) {
		if (str == null || "".equals(str.trim())) {
			return false;
		}
		Pattern pattern = Pattern.compile("[0-9]*(\\.?)[0-9]*");
		return pattern.matcher(str).matches();
	}

	public static boolean lessThan(String str, int len) {
		if (len <= 0) {
			return false;
		} else {
			if (str == null || "".equals(str.trim())) {
				return true;
			} else if (str.trim().length() <= len) {
				return true;
			} else {
				return false;
			}
		}
	}

}